package modules

import (
	"PDF/utils"
	"fmt"
	"time"

	"github.com/asaskevich/govalidator"
	"gorm.io/gorm"
)

type UserBasic struct {
	ID         uint64 `gorm:"primaryKey"`
	Name       string
	Password   string
	Email      string `valid:"email"`
	LoginTime  time.Time
	LogoutTime time.Time
}

func CreateUser(user *UserBasic) error {
	db, _ := utils.InitMySQL()
	result := db.Create(&user)
	if result.Error != nil {
		fmt.Println("用户创建失败")
		return result.Error
	}
	return nil
}

func FindUserbyID(id uint64) (*UserBasic, error) {
	user := UserBasic{}
	db, _ := utils.InitMySQL()
	result := db.First(&user, id)
	if result.Error != nil {
		fmt.Println("根据ID查询失败，错误为：", result.Error)
		return nil, result.Error
	} else {
		return &user, nil
	}
}

func FindUserbyName(Name string) (*UserBasic, error) {
	user := UserBasic{}
	db, _ := utils.InitMySQL()
	result := db.Where("name = ?", Name).First(&user)
	if result.Error != nil {
		fmt.Println("根据用户名查询失败，错误为：", result.Error)
		return nil, result.Error
	} else {
		return &user, nil
	}
}

func Login(UserName string, Password string) {

}

func CheckUpdates(db *gorm.DB, user *UserBasic, id uint64) error {
	db.First(user, id)
	_, err := govalidator.ValidateStruct(user)
	if err != nil {
		fmt.Println("数据校验失败，错误为：", err)
		return err
	}
	return nil
}

func UpdatesUser(id uint64, user *UserBasic) error {
	db, _ := utils.InitMySQL()
	result := db.Table("user_basic").Where("id = ?", id).Updates(user)
	if result.Error != nil {
		fmt.Println("数据更新失败，错误原因为：", result.Error.Error())
		return result.Error
	}
	if CheckUpdates(db, user, id) != nil {
		return CheckUpdates(db, user, id)
	} else {
		return nil
	}
}
